<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Repositories\Contracts\UserRepositoryInterface;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Log;

class UserController extends Controller
{

  private $userRepository;

  public function __construct(UserRepositoryInterface $userRepository)
  {
    $this->userRepository = $userRepository;
  }

  public function lists()
  {
    $result = $this->userRepository->paginate();
    return $this->result(true, $result);
  }


  public function info($userId)
  {
    $user = $this->userRepository->get_user_and_role($userId);
    return $this->resultData($user);
  }

  /**
   * 管理员，对用户进行修改，新增操作
   *
   * @param Request $request
   *
   * @return \Illuminate\Http\JsonResponse
   */
  public function save(Request $request)
  {

    $data = $request->only('name', 'email', 'password');
    $id = intval($request->post('id'));
    $this->validation($request, $id);
    $data = $this->userRepository->save($data, $id);
    return $this->result($data != null, $data);
  }

  public function remove($id = 0)
  {
    $id = intval($id);
    // 是正整数时，不是自己时可以删除
    if ($id > 0 && $id != Auth()->user()->id) {
      return $this->result($this->userRepository->delete($id));
    } else {
      return $this->result(false);
    }
  }




  protected function validation($request, $id)
  {

    $user = [
      'name' => ['required', 'string', 'max:255'],
      'email' => ['required', 'email'],
    ];
    if ($id < 1) {
      // 新用户做唯一性检测
      $user['name'][] = "unique:users,name";
      $user['email'][] = "unique:users,email";
      $user['password'] = ['required', 'string'];
    } else {
      $user['name'][] = Rule::unique('users')->ignore($id);
      $user['email'][] = Rule::unique('users')->ignore($id);
    }

    $this->validateWith($user, $request);
  }

  public function save_role(Request $request)
  {
    $userId = intval($request->input('userId'));
    $roles = $request->input("roles");
    return $this->result($this->userRepository->save_role($userId, $roles));
  }
}
